/* eslint-disable max-len */
/* eslint-disable no-multiple-empty-lines */
/* eslint-disable prettier/prettier */
import camelCase from 'camelcase';
import _map from 'lodash/map';
import _ from 'lodash';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import React, { Component, useState, createRef} from 'react';
import { View, StyleSheet, Text, TouchableOpacity, Image, FlatList, Dimensions } from 'react-native';
import { Divider, Utils, TYFlatList, Popup, TopBar, BrickButton, TYText, Dialog, Toast, Modal } from 'tuya-panel-kit';
import { AnySizeDragSortableView,AutoDragSortableView } from 'react-native-drag-sort';
import Res from '../../res';
import TYSdk from '../../api';
import dpCodes from '../../config/dpCodes';
import { arrayToObject, debounce } from '../../utils';
import Strings from '../../i18n';
import kColor from "../../config/kColor";


const { convertX: cx } = Utils.RatioUtils;
const { convertY: cy, viewWidth, viewHeight } = Utils.RatioUtils;

const TYEvent = TYSdk.event;
const TYDevice = TYSdk.device;
const textStyle = {
  height: 64,
  color: '#333',
  justifyContent: 'center',
  alignItems: 'center',
  textAlign: 'center',
  backgroundColor: '#fff',
};

const {
  work_mode: work_modeCode,
} = dpCodes;


class LightModeScene extends Component {
  constructor(props) {
    super(props);
    this.sortableViewRef = createRef();
    const { work_mode } = this.props;
    this.flage = false;
    this.state = {
      isEditing: false,
      showToast: false,
      toastTips: '',
      count: 0,
      basicVisible: false,
      Arraydata: TYSdk.getLightModeList(),
    };
  }

  getModeData() {
    const modeString = TYSdk.device.getState('light_mode_list');
    console.log(modeString);
    const modeArray = modeString.split(',');
    console.log(modeArray);
    let modeData = [];
    for (let i = 0; i < modeArray.length; i++) {
      let modelength = modeArray[i].length;
      console.log(modelength);
      if ( modelength === 1) {
        // 默认模式
        let obj;
        switch (modeArray[i]) {
          case '0':
            obj = {
              key: i,
              title: '日光',
              work_mode: 'Day',
            };
            modeData.push(obj);
            break;
          case '1':
            obj = {
              key: i,
              title: '流光',
              work_mode: 'Flow',
            };
            modeData.push(obj);
            break;
          case '2':
            obj = {
              key: i,
              title: '水草灯',
              work_mode: 'Grass',
            };
            modeData.push(obj);
            break;
          case '7':
            obj = {
              key: i,
              title: '夜灯模式',
              work_mode: 'Night',
            };
            modeData.push(obj);
            break;
          default:
            break;
        }
      } else {
        // 自定义模式
        let getCustom = modeArray[i].split('-');
        let obj;
        console.log(getCustom);
        if (getCustom[2] === '3') {
          obj = {
            key: i,
            title: '白光',
            work_mode: 'Color1',
          };
          modeData.push(obj);
        } else if (getCustom[2] === '4') {
          obj = {
            key: i,
            title: '南美风',
            work_mode: 'Color2',
          };
          modeData.push(obj);
        } else if (getCustom[2] === '5') {
          obj = {
            key: i,
            title: '溪流风',
            work_mode: 'Color3',
          };
          modeData.push(obj);
        } else if (getCustom[2] === '6') {
          obj = {
            key: i,
            title: getCustom[1],
            work_mode: 'Color4',
          };

          modeData.push(obj);
        } else if (getCustom[2] === '8') {
          obj = {
            key: i,
            title: getCustom[1],
            work_mode: 'Color5',
          };
          modeData.push(obj);
        } else if (getCustom[2] === '9') {
          obj = {
            key: i,
            title: getCustom[1],
            work_mode: 'Color6',
          };
          modeData.push(obj);
        } else if (getCustom[2] === '10') {
          obj = {
            key: i,
            title: getCustom[1],
            work_mode: 'Color7',
          };
          modeData.push(obj);
        } else if (getCustom[2] === '11') {
          obj = {
            key: i,
            title: getCustom[1],
            work_mode: 'Color8',
          };
          modeData.push(obj);
        }
      }
    }
    return modeData;
  }

  addBtn() {
    return (
      <View style={{ height: 80, marginBottom: 35, flexDirection: 'column', alignItems: 'center', justifyContent: 'space-between' }}>
        {/* 最多可添加至8个模式 */}
        <Text style={[ kColor.theme[kColor.type].subTitleColor, {fontSize: 15}]}>{Strings.light_mode_button_create_desc}</Text>
        <BrickButton
          text={Strings.page_title_create_schedule}// "新建"
          textStyle={{fontSize: 16}}
          wrapperStyle={kColor.theme[kColor.type].btnBgBlueColor}
          onPress={()=>{
            const modeString = TYSdk.device.getState('light_mode_list');
            const modeArray = modeString.split(',');
            if (modeArray.length < 8) {
              this.showModal();
            } else {
              Dialog.alert({
                title: '超过数量',
                subTitle: '灯光模式数量已达最大数',
                confirmText: '确认',
                onConfirm: (data, { close }) => {
                  close();
                },
              });
            }
          }}
        />
      </View>
    );
  };

  toastView(show, tips ) {
    const { showToast, toastTips } = this.state;
    return (
      <Toast show={showToast} text={toastTips} onFinish={() => {
        this.setState( {showToast: false });
      }}
      />
    );
  }

  cellView(item, index) {
    // console.log(item);
    //const { movedKey } = this.state;
    let liststyle;
    if (this.state.isEditing && (item.work_mode == 'Day' || item.work_mode == 'Flow' || item.work_mode == 'Grass')) {
      liststyle = styles.showMainList;
    } else if (this.state.isEditing && item.work_mode !== 'Day' && item.work_mode !== 'Flow' && item.work_mode !== 'Grass') {
      liststyle = styles.showSubList;
    } else if (!this.state.isEditing) {
      liststyle = styles.hiddenList;
    }
    return (

      <View style={styles.cell}>

        <View style={styles.iconAndText}>
          <View style={this.state.isEditing && item.work_mode !== 'Day' && item.work_mode !== 'Flow' && item.work_mode !== 'Grass' ? styles.showDelete : styles.hiddenDelete}>
            <TouchableOpacity
              style={styles.deleteIcon}
              onPress={() => {
                { item.isBind === '' ? this.delClick(item.key, index) : this.setState( {showToast: true, toastTips: item.isBind });}
              }}
            >
              <Image style={{ width: 22, height: 22, marginLeft:20}} source={Res.fdelete} resizeMode="stretch" />
            </TouchableOpacity>
          </View>
          {
            item.icon && !this.state.isEditing ? (
              <Image style={styles.icon} source={item.icon} resizeMode="stretch" />
            ) : item.icon && this.state.isEditing ? (
              <Image style={styles.marginicon} source={item.icon} resizeMode="stretch" />
            ) : item.color && !this.state.isEditing ? (
              <View style={{ alignItems: 'center', justifyContent: 'center', position: 'absolute', left: 20, width: 36, height: 36, borderRadius: 24, backgroundColor: item.color }} />
            ) : item.color && this.state.isEditing ? (
              <View style={{ alignItems: 'center', justifyContent: 'center', position: 'absolute', left: 42, width: 36, height: 36, borderRadius: 24, backgroundColor: item.color }} />
            ) : undefined
          }
          <Text style={[ kColor.theme[kColor.type].titleColor, this.state.isEditing ? styles.editTitle : styles.cellTitle]}>{`${item.title}`}</Text>
        </View>

        <View style={ this.state.isEditing ? styles.hiddenButton : styles.showButton}>
          <BrickButton
            text={Strings.light_mode_button_title_apply}
            textStyle={[ kColor.theme[kColor.type].blueColor,{ fontSize: 13 }]}
            wrapperStyle={[ kColor.theme[kColor.type].btnBgLightBlueColor, { width: 83, height: 34, borderRadius: 17 }]}
            loadingSize="large"
            // style={{ marginEnd: 27 }}
            onPress={() => {
              TYDevice.putDeviceData({
                work_mode: item.work_mode,
              });
            }}
          />
        </View>

        <View style={this.state.isEditing && item.work_mode !== 'Day' && item.work_mode !== 'Flow' && item.work_mode !== 'Grass' && item.work_mode !== 'Night' && item.work_mode !== 'Color1' && item.work_mode !== 'Color2' && item.work_mode !== 'Color3' ? styles.showEdit : styles.hiddenEdit}>
          <TouchableOpacity
            onPress={() => {
              TYSdk.Navigator.push({
                id: 'customLight',
                listitem: item,
              });
            }}
          >
            <Image style={{ width: 22, height: 22}} source={Res.fedit} resizeMode="stretch" />
          </TouchableOpacity>
        </View>

        <View style={liststyle}>
          {/* <TouchableOpacity
            onLongPress={() => {
              console.log('pressing');
            }}> */}
          
          <Image style={{width: 22, height: 22}} source={Res.flist} resizeMode="stretch" />
          {/* </TouchableOpacity> */}
        </View>
      </View>

    );
  };

  checkAdd(item, index) {
    console.log(item);
    const NowModeString = TYSdk.device.getState('light_mode_list');
    const NowModeArray = NowModeString.split(',');
    if (NowModeArray.includes(item.value)) {
      return (
        <View style={{
          flexDirection: 'row', // 设置子元素水平排列
          alignItems: 'center', // 垂直居中子元素（可选）
          marginTop: 10,
          marginBottom: 10,
        }}
        >
          <Image style={{width: 45, height: 45, marginLeft: 20, marginRight: 10}} source={item.icon} resizeMode="stretch" />
          <Text style={[kColor.theme[kColor.type].rightTitleColor, {fontSize: 16, fontWeight: 'bold'}]}>{`${item.title}`}</Text>
          <View style={{position: 'absolute', left: 300}}>
            <Text style={[kColor.theme[kColor.type].rightTitleColor,{fontSize: 16}]}>{Strings.light_mode_added_title}</Text>
          </View>
        </View>
      );
    } else {
      return (
        <TouchableOpacity
          onPress={()=>this.hiddenModal(item)}
        >
          <View style={{
            flexDirection: 'row', // 设置子元素水平排列
            alignItems: 'center', // 垂直居中子元素（可选）
            marginTop: 10,
            marginBottom: 10,
            marginLeft: 20,
          }}
          >
            <Image style={{width: 45, height: 45, marginRight: 10}} source={item.icon} resizeMode="stretch" />
            <Text style={[kColor.theme[kColor.type].titleColor,{fontSize: 16, fontWeight: 'bold' }]}>{`${item.title}`}</Text>
          </View>
        </TouchableOpacity>
      );
    }
  }

  topView() {
    return (
      <TopBar.Container
        backgroundColor={kColor.type === 'dark'?"#020202":"#f4f4f4"}
        style={{ height: TopBar.height }}
        contentStyle={{ height: TopBar.height, marginTop: 10 }}
      >
        <TopBar.Action size={20} source={Res.fback} color="#4C4C4C" onPress={() => TYSdk.Navigator.pop()} />
        <TopBar.Content />
        <TopBar.Action
          source={Res.fedit}
          color="#4C4C4C"
          size={20}
          style={{marginTop: 700}}
          onPress={() => {
            // 点击右上角进入、退出编辑状态
            this.setState({ isEditing: !this.state.isEditing });
          }}
        />
      </TopBar.Container>
    );
  }

  topEditing() {
    return (
      <TopBar.Container
        backgroundColor={kColor.type === 'dark'?"#020202":"#f4f4f4"}
        style={{ height: TopBar.height }}
        contentStyle={{ height: TopBar.height, marginTop: 10 }}
      >
        <TopBar.Action size={20} source={Res.fback} color="#4C4C4C" onPress={() => TYSdk.Navigator.pop()} />
        <TopBar.Content />
        <TopBar.Action
          source={Res.ftack}
          color="#4C4C4C"
          size={20}
          style={{marginTop: 500}}
          onPress={() => {
            // 点击右上角进入、退出编辑状态
            this.setState({ isEditing: !this.state.isEditing });
          }}
        />
      </TopBar.Container>
    );
  }

  delClick = debounce((key, index) => {
    Dialog.confirm({
      title: '删除灯光模式',
      subTitle: '你确认删除这个灯光模式吗',
      cancelText: '取消',
      confirmText: '确认',
      confirmTextStyle: { fontSize: 16, fontWeight: 'bold', color: '#22a8dc' },
      onConfirm: (data, { close }) => {
        const modeString = TYSdk.device.getState('light_mode_list');
        const modeArray = modeString.split(',');
        // modeArray.splice(key, 1); // 应该用索引下标，不是key
        modeArray.splice(index, 1);
        const NewModeString = modeArray.join(',');
        console.log(NewModeString);
        TYDevice.putDeviceData({
          light_mode_list: NewModeString,
        });
        close();

      },
    });


  });

  newRanking(data) {
    const dataArray = Object.values(data);
    console.log(Object.values(dataArray));
    let newArray = [];
    dataArray.forEach((item, index) => {
      newArray.push(item.string);
    });
    const newRanking = newArray.toString();
    //console.log("newRanking:"+newRanking);

    Dialog.confirm({
      title: '更改灯光模式位置',
      subTitle: '确认更改这个灯光模式位置吗',
      cancelText: '取消',
      confirmText: '确认',
      confirmTextStyle: { fontSize: 16, fontWeight: 'bold', color: '#22a8dc' },
      onConfirm: (data, { close }) => {
        console.log(newRanking);
        TYDevice.putDeviceData({
          light_mode_list: newRanking,
        });
        close();
      },
    });
    this.setState({ isEditing: !this.state.isEditing });
  }

  showModal() {
    console.log('show');
    const { basicVisible } = this.state;
    this.setState({ basicVisible: true});
  }

  hiddenModal(item) {
    //console.log('hidden:'+item);
    const { basicVisible } = this.state;
    this.setState({ basicVisible: false});
    const modeArray = TYSdk.getLightModeList();
    console.log('array:'+modeArray);
    let customCount = 0;
    let modeKeyString = [];
    modeArray.forEach(itemB => {
      if (itemB.work_mode === 'Color4' || itemB.work_mode === 'Color5' || itemB.work_mode === 'Color6' || itemB.work_mode === 'Color7' || itemB.work_mode === 'Color8') {
        customCount++;
        modeKeyString.push(itemB.key);
      }
    });
    if ( customCount >= 5) {
      Dialog.alert({
        title: Strings.light_mode_button_create_desc, //'超过数量',
        subTitle: '', //'自定义灯光模式数量已达最大数',
        confirmText: Strings.ok, //'确认',
        onConfirm: (data, { close }) => {
          close();
        },
      });
    } else if (item.key == 10) {
      TYSdk.Navigator.push({
        id: 'customLight',
        listdata: modeKeyString,
      });
    } else {
      const modeArrayString = TYSdk.device.getState('light_mode_list');
      const NewModeString = `${modeArrayString},${item.value}`;
      console.log(`NewModeList:${NewModeString}`);
      TYDevice.putDeviceData({
        light_mode_list: NewModeString,
      });
    }
  }


  render() {
    const { light_mode_list } = this.props;
    const { isEditing, showToast, toastTips, basicVisible } = this.state;
    // const Arraydata = this.getModeData();
    // const renderItem = ({ item, index, isMoved }) => (this.cellView(item, index, isMoved));
    const addItem = ({ item, index }) => (this.checkAdd(item, index));
    const addData = [
      {
        key: '4',
        title: '南美风',
        value: '16724753-hfjh_nmg-4',
        icon: 23
      },
      {
        key: '5',
        title: '溪流风',
        value: '14279679-hfjh_xlg-5',
        icon: 24
      },
      {
        key: '3',
        title: '白光',
        value: '16777215-hfjh_white-3',
        icon: 25
      },
      {
        key: '7',
        title: '夜灯模式',
        value: '7',
        icon: 26
      },
      {
        key: '10',
        title: '自定义',
        value: 'Custom',
        icon: 28
      },
    ];

    return (
      <View style={[styles.container, kColor.theme[kColor.type].pageBgColor]}>
        {!isEditing ? this.topView() : null}

        {isEditing ? this.topEditing() : null}

        <View style={{ height: 50, flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between' }}>
          {/* 灯光模式 */}
          <Text style={[ kColor.theme[kColor.type].pageTitleColor, { marginStart: 20, fontSize: 30 }]}>{Strings.page_title_light_mode_list}</Text>
        </View>

        <AutoDragSortableView
          ref={this.sortableViewRef}
          dataSource={this.state.Arraydata}
          parentWidth={360}
          childrenWidth={360}
          marginChildrenBottom={0}
          marginChildrenRight={0}
          marginChildrenLeft = {0}
          marginChildrenTop={0}
          childrenHeight={60}
          keyExtractor={(item, index) => item.key}
          onDataChange={(data) => {
            console.log(data);
            this.setState({
              Arraydata: data
            });
          }}
          renderItem={
            ( item, index ) => {return this.cellView(item, index);}
          }
          onDragEnd={() => {
            console.log('drag end');
          }}
        />

        <Modal
          visible={this.state.basicVisible}
          onMaskPress={() => this.setState({ basicVisible: false })}
        >
          <View style={[styles.textStyle, kColor.theme[kColor.type].homeCardBgColor]}>
            <View style={{alignItems: 'center', height: 20, flex: 1, marginTop: 10}}>
              <Text style={[kColor.theme[kColor.type].titleColor, {fontSize: 20, fontWeight: 'bold'}]}>{Strings.page_title_create_mode}</Text>
            </View>
            <FlatList
              data={addData}
              renderItem={addItem}
              keyExtractor={(item) => item.key}
            />
            <View style={{alignItems: 'center', flex: 1, marginBottom: 30}}>
              <BrickButton
                text={Strings.cancel}// "取消"
                textStyle={[kColor.theme[kColor.type].titleColor, {fontSize: 16}]}
                wrapperStyle={ kColor.theme[kColor.type].btnBgLightGrayColor }
                onPress={()=>{
                  this.setState({ basicVisible: false });
                }}
              />
            </View> 
          </View>
        </Modal>

        {!isEditing ? this.addBtn() : null}

        {isEditing ? this.toastView() : null}

      </View>
    );
  }

}

// LightModeScene.propTypes = {
//   onChangeList: PropTypes.func.isRequired,
// };

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#ffffff',
    height: 500,
  },
  cell: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
    // backgroundColor: '#fff',
    height: 72,
    width: Dimensions.get('window').width,
  },
  cellTitle: {
    position: 'absolute',
    left: 78,
    fontSize: 16,
    fontWeight: 'bold',
    // color: '#000',
  },
  editTitle: {
    position: 'absolute',
    left: 100,
    fontSize: 16,
    fontWeight: 'bold',
    // color: '#000',
  },
  iconAndText: {
    flexDirection: 'row',
    alignItems: 'center',
  },
  icon: {
    justifyContent: 'center',
    position: 'absolute',
    left: 20,
    width: 36,
    height: 36,
    borderRadius: 18,
  },
  marginicon: {
    justifyContent: 'center',
    position: 'absolute',
    left: 42,
    width: 36,
    height: 36,
    borderRadius: 18,
  },
  showDelete: {
    display: 'flex',
  },
  hiddenDelete: {
    display: 'none',
  },
  showSubList: {
    marginRight:10,
  },
  showMainList: {
    marginRight:10,
  },
  hiddenList: {
    display: 'none',
  },
  showEdit: {
    marginRight:-250,
  },
  hiddenEdit: {
    display: 'none',
  },
  showButton: {
    //position:'absolute',
    //left: 280,
    marginRight: 20
  },
  hiddenButton: {
    display: 'none',
  },

  deleteIcon: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'center',
    width: 30,
    height: 30,
  },

  textStyle: {
    height: 500,
    borderTopLeftRadius: 20,
    borderTopRightRadius: 20,
    backgroundColor: '#fff',
  },
  

});

export default connect(({ dpState }) => ({
  dpState,
  // light_mode_list: dpState[light_mode_list],
  work_mode: dpState[work_modeCode],
}))(LightModeScene);


